import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

// 
/* 
    重复点一个路由报错问题   
    1、降级router
    2、在push方法中捕获异常
    3、以下修改原型方法 把以下代码粘贴到 Vue.use(VueRouter)之前
 */
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function(location) {
    return originalPush.call(this, location).catch(err => {
        // console.log(err);
    })
};

Vue.use(VueRouter)

const routes = [{
        path: '/',
        redirect: '/home'
    },
    {
        path: '/home',
        name: 'Home',
        component: Home,
        meta: {
            activeNum: 0
        },
        children: [{
            path: '/home/searchPopup',
            name: 'SearchPopup',
            component: () =>
                import ('../views/SearchPopup.vue')
        }]
    },
    {
        path: '/category',
        name: 'Category',
        meta: {
            activeNum: 1
        },
        component: () =>
            import ('../views/Category.vue')
    },
    {
        path: '/cart',
        name: 'Cart',
        meta: {
            activeNum: 2
        },
        component: () =>
            import ('../views/Cart.vue')
    },
    {
        path: '/user',
        name: 'User',
        meta: {
            activeNum: 3
        },
        component: () =>
            import ('../views/User.vue')
    },
]

const router = new VueRouter({
    routes
})

// 路由拦截/路由守卫，在跳转路由之前拦截下来，判断是否获取到token
router.beforeEach((to, from, next) => {
    console.log("to" + to);
    console.log("from" + from);
    // to要去的路由对象
    // from从哪里来的路由对象
    let token = localStorage.getItem("token");
    if (to.path == "/cart") {
        if (token) {
            next()
        } else { //1、跳转到购物车页面2、是否存在token
            Vue.prototype.$toast('请先登录！');
            next("/user") //跳转到我的页面
        }
        return
    }
    next();
})

export default router